package com.example.petchating.android.api

import android.content.Context
import com.example.petchating.android.retrofit.DashScopeRetrofitClient
import com.example.petchating.android.retrofit.EmotionInput
import com.example.petchating.android.retrofit.EmotionRequest
import com.example.petchating.network.EmotionService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.HttpException

class AndroidEmotionService(private val context: Context) : EmotionService {

    override fun analyzeEmotion(message: String, callback: (String) -> Unit) {
        CoroutineScope(Dispatchers.IO).launch {
            val request = EmotionRequest(
                input = EmotionInput(sentence = message)
            )

            try {
                val response = DashScopeRetrofitClient.apiService.analyzeEmotion(request)
                val result = if (response.isSuccessful) {
                    response.body()?.output?.text?.replace(";", "") ?: "未知情绪"
                } else {
                    "分析失败：${response.code()}"
                }

                withContext(Dispatchers.Main) {
                    callback(result)
                }

            } catch (e: Exception) {
                val error = when (e) {
                    is HttpException -> "网络错误：${e.code()}"
                    else -> "请求异常：${e.message}"
                }

                withContext(Dispatchers.Main) {
                    callback(error)
                }
            }
        }
    }
}


